import ms from 'ms';

export function intervalToMillis(config = {}) {
	const { num, unit } = config;

	switch (unit) {
		case 'month':
			return ms(`${num * 30}d`);
		case 'week':
			return ms(`${num * 7}d`);
		default:
			return ms(`${num}${unit}`);
	}
}

/**
 * 获取下次执行需要等待的毫秒数
 **/
export default function nextExecMillis(interval) {
	if (!interval) return 0;

	const now = Date.now();
	const every = intervalToMillis(interval);
	const start = new Date(interval.startTime || now).getTime();
	const ret = now - (now % every) + (start % every);
	const next = ret < now ? ret + every : ret;

	return next - now;
}
